/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dormouse.vfs.ui.renderers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.prefs.Preferences;

/**
 * This factory is responsible for creating instances of the IFileListRenderer.
 * 
 */
public class FileListRendererFactory {

	private static Map<String, IFileListRenderer> fileListRendererMap = new HashMap<String, IFileListRenderer>();
	private static List<IFileListRenderer> rendererList = new ArrayList<IFileListRenderer>();

	static {
		ServiceLoader<IFileListRenderer> loader = ServiceLoader
				.load(IFileListRenderer.class);
		Iterator<IFileListRenderer> it = loader.iterator();
		IFileListRenderer renderer = null;
		while (it.hasNext()) {
			renderer = (IFileListRenderer) it.next();
			fileListRendererMap.put(renderer.getName(), renderer);
			rendererList.add(renderer);
		}
	}

	/**
	 * This method gets the file list renderer by using it's name.
	 * 
	 * @param rendererName
	 * @return a file list renderer
	 */
	public static IFileListRenderer getInstance(String rendererName) {
		return fileListRendererMap.get(rendererName);
	}

	/**
	 * This method gets the default file list renderer. If the user has made a
	 * choice for default renderer, then that renderer is used, otherwise the
	 * first renderer in the renderer list is chosen.
	 * 
	 * @return the default file list renderer.
	 */
	public static IFileListRenderer getDefaultInstance() {

		Preferences root = Preferences
				.userNodeForPackage(FileListRendererFactory.class);
		String rendererName = root.get("rendererName", null);
		if (rendererName == null) {
			return rendererList.get(0);
		} else {
			return getInstance(rendererName);
		}
	}

	/**
	 * This method gets a list of renderers suitable for use in a combo box.
	 * 
	 * @return the list of registered renderers.
	 */
	public static List<IFileListRenderer> getRenderers() {
		return rendererList;
	}

}
